package cn.piggy.gateway.core.session.simple;

import cn.piggy.gateway.core.config.ConfigHelper;
import cn.piggy.gateway.core.datasource.connection.Connection;
import cn.piggy.gateway.core.datasource.DataSource;
import cn.piggy.gateway.core.datasource.DataSourceFactory;
import cn.piggy.gateway.core.datasource.unpooled.UnpooledDataSourceFactory;
import cn.piggy.gateway.core.executor.SimpleExecutor;
import cn.piggy.gateway.core.http.HttpStatement;
import cn.piggy.gateway.core.session.GatewaySession;
import cn.piggy.gateway.core.session.GatewaySessionFactory;


public class SimpleGatewaySessionFactory implements GatewaySessionFactory {

    private final ConfigHelper configHelper;

    public SimpleGatewaySessionFactory(ConfigHelper configHelper) {
        this.configHelper = configHelper;
    }

    @Override
    public GatewaySession openSession(String uri) {
        // 获取数据源连接信息：这里把 dubbo、HTTP 抽象为一种连接资源
        DataSourceFactory dataSourceFactory = new UnpooledDataSourceFactory(configHelper, uri);
        DataSource dataSource = dataSourceFactory.getDataSource();
        Connection connection = dataSource.getConnection();
        // 创建执行器
        SimpleExecutor baseExecutor = new SimpleExecutor(connection);
        // 创建会话：DefaultGatewaySession
        HttpStatement httpStatement = configHelper.getHttpStatement(uri);
        return new SimpleGatewaySession(httpStatement, baseExecutor);
    }

    @Override
    public ConfigHelper getConfigHelper() {
        return configHelper;
    }

}
